package com.orhon.smartcampus.modules.systemctl.mutation;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.orhon.smartcampus.basicComponents.Result;
import com.orhon.smartcampus.modules.systemctl.dao.ApisDao;
import com.orhon.smartcampus.modules.systemctl.dao.OperationApiDao;
import com.orhon.smartcampus.modules.systemctl.entity.Apis;
import com.orhon.smartcampus.modules.systemctl.entity.OperationApi;
import com.orhon.smartcampus.modules.systemctl.gqlInputModel.GQLOperationApiInput;
import com.orhon.smartcampus.modules.systemctl.inputMapper.OperationApiInputMapper;

import graphql.schema.DataFetcher;
import graphql.schema.DataFetchingEnvironment;

@Component
public class AddOperationApiMutation implements DataFetcher {

	@Autowired
	OperationApiDao operationApiDao;
	@Autowired
    ApisDao apisDao;

	@Override
	@Transactional
	public Object get(DataFetchingEnvironment environment) throws Exception {


		GQLOperationApiInput input = OperationApiInputMapper.MAPPER.mapInput(environment.getArgument("inputData"));
		
		List<OperationApi> list = new ArrayList<OperationApi>();
		
		if (input.getApi_id() != null) {
			List<Integer> api_ids = input.getApi_id();
			for (Integer api_id : api_ids) {
				OperationApi operationApi = new OperationApi();
				operationApi.setApi_id(api_id);
				Apis apis = apisDao.findById(Long.valueOf(api_id));
				if(apis==null) {
					continue;
				}
				operationApi.setApi_code(apis.getCode());
				operationApi.setOperation_id(input.getOperation_id());
				operationApiDao.save(operationApi);
				list.add(operationApi);
			}
		}
		return Result.ok().put("data", list);
	}
}

